import sys
import os.path
from subprocess import call
import subprocess
import shutil

inputFolder = "Z:\\movies\\";
outputFolder = "Z:\\pictures\\movies\\";
hbFolder = "C:\\Program Files\\Handbrake\\";
tempFolder = "C:\\Temp\\"

print("using encodeDVD_v4.py")

for filename in os.listdir (inputFolder):
    fileRoot, fileExtension = os.path.splitext(filename)
    if (".ISO" == fileExtension):
        inputFile = inputFolder + filename
        outputFile = outputFolder + fileRoot + ".m4v"
        hb = hbFolder + "HandBrakeCLI"

        if (True == os.path.exists(outputFile)):
            print(outputFile + " already exists!");
        else:
            p1 = subprocess.Popen([hb, '-i', inputFile, '--scan'], stderr=subprocess.PIPE)
        
            (stdoutdata, stderrdata) = p1.communicate()

            str = stderrdata.decode("utf-8", "strict")
            lines = str.split('\n')
            audio = "none"
            rank = 20
            new_rank = 20
            audioline = "none"
            for line in lines:
                print(line)
                if ((-1 != line.find("(AC3)")) and (-1 != line.find("+")) and (-1 != line.find("English"))):
                    if (-1 != line.find("(5.1 ch)")):
                        new_audioline = line
                        new_rank = 1
                    elif (-1 != line.find("(5.0 ch)")):
                        new_audioline = line
                        new_rank = 2
                    elif (-1 != line.find("(2.0 ch)")):
                        new_audioline = line
                        new_rank = 3
                    elif (-1 != line.find("(1.0 ch)")):
                        new_audioline = line
                        new_rank = 4
                    print(new_audioline);
                    print(new_rank);
                    if (new_rank < rank):
                        audioline = new_audioline
                        rank = new_rank

            if ("none" != audioline):
                print("best audio track is: " + repr(audioline))
                audio_s = line.find("+")
                audio_e = line.find(",")
                audio = line[audio_s+2:audio_e]
                   
                command = hb + " -i " + inputFile + " -t 1 -o " + outputFile + " -m -f mp4 –strict-anamorphic -e x264 -a \"" + audio + "\" -E copy --vfr -x b-adapt=2:rc-lookahead=50"

                print(command)

                call(command)
            else:
                print("failed to find audio track for " + fileRoot)
                                  
            print("done ripping")
